import os
import re

__NEW_LINE__ = "\n"

class FileStore:
    """Use this class to make it easier to write to files"""
    def __init__(self):
        self.f = None
        pass
    
    def createFile(self, filename):
        """Creates a file in the current dir, only suplly the filename, not the complete path!"""
        __dir__ = os.path.dirname(os.path.abspath(__file__))
        # filename = "fetch" + str(index) + ".txt"
        filepath = os.path.join(__dir__, filename)
        print filepath
        #f = codecs.open('test', encoding='utf-8', mode='w')
        self.f = open(filepath, 'w')
        return self.f
    
    def writeLine(self, text):
        """Writes a line to the file and append NEW_LINE, file should be created first"""
        line = "".join([text, __NEW_LINE__])
        self.f.write(line)
        
    def writeCleanLine(self, text):
        """Writes a clean line, trim text, remove linebreaks and check encoding"""
        try:
            cleantext = self.cleanString(text.strip())
            if (len(cleantext) > 0):
                self.writeLine(cleantext)
        except UnicodeEncodeError, e:
            #print "unicode error: " + unicode(line,'Latin-1' ,'replace')
            #print "unicode error: " + unicode(line,'Latin-1' ,'replace')
            #print line.encode('utf8')
            print "FileManager:" + text.encode('utf8')
            
    def cleanString(self, text):
        """Cleans the string text, trim text, remove tabs/newline"""
        lineBreak = __NEW_LINE__
        r = re.compile(lineBreak)    
        splitted = r.split(text)
        oneline = "".join(splitted)
        return oneline
    
    def closeFile(self):
        self.f.close()
    